# -*-coding:utf-8-*-
from qiniu import Auth, put_file, put_data
import time
from django.conf import settings

bucket_name = 'dkzcm-python'
q = Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY)


def upload_file(path, key=None, prefix='blog/'):
    """"
    :param path: 图片路径
    :param key: 图片上传之后的名字
    :param prefix: 图片前缀
    :return: 在线路径
    """
    # 如果不上传名字
    if not key:
        key = prefix + str(int(time.time())) + '.' + path.split('.')[-1]
    else:
        key = prefix + key + '.' + path.split('.')[-1]
    # 生成上传token
    token = q.upload_token(bucket_name, key, 2)

    put_file(token, key, path, version='v1')
    return 'http://image.dkzcm.club/' + key


def upload_data(file_data, key=None, suffix='.png', prefix='blog/'):
    '''

    :param file_data: 图片的字节数据
    :param key:图片上传后的名字
    :param suffix:
    :param prefix:
    :return:
    '''
    if not key:
        key = prefix + str(int(time.time())) + suffix
    else:
        key = prefix + key + suffix
    # 生成上传token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 2)
    put_data(token, key, file_data)
    return 'http://image.dkzcm.club/' + key
